//
// Created by v on 19-7-2.
//

#include <unistd.h>

#include "CMCoapServer.h"
#include "utils/cm_logprint.h"

CMLogPrint logPrint;

static int toBroad = 0;

class CMCoapFunctionAction : public CMCoapFunction
{
  public:
    int onRecvData(const char *url, std::string data)
    {
        cminfo("recv url [%s] [%s]\n", url, data.c_str());
        toBroad = 1;
        return 0;
    }

    void addHandler(CMCoapServer *s) { m_handler = s; }

  private:
    CMCoapServer *m_handler;
};

int main(int argc, char **args)
{
    CM_LOG_PRINT_INIT("coap");
    const char *addr = args[1];
    int         port = strtol(args[2], NULL, 10);

    cminfo("do with addr [%s][%d]\n", addr, port);

    CMCoapServer::startup();
    CMCoapFunctionAction *action = new CMCoapFunctionAction();
    CMCoapServer *        s      = new CMCoapServer(addr, port);
    s->setCoapCallback(action);
    action->addHandler(s);
    s->setDebug(true);
    cminfo("program init\n");
    int ret = s->init();
    if (ret < 0)
    {
        cmerror("init fail [%d]\n", ret);
        return -1;
    }

    cminfo("add resource\n");
    s->addResource("qlink/netinfo");

    const char *successStr =
        "{\"deviceMac\":\"D8B6C103058A\", \"deviceType\":\"500534\"}";
    int suclen = strlen(successStr);

    cminfo("start run cycle\n");
    int count = 0;
    while (count++ < 12000)
    {
        int ret = s->run_once();
        if (ret < 0)
        {
            usleep(500);
        }
    }
    cminfo("program exit...\n");

    delete s;
    delete action;
    CMCoapServer::cleanup();
    cminfo("done, exit...\n");
    getchar();
    return 0;
}
